package com.dolawing.phonecallapp.blacknumber.function;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.provider.CallLog;
import android.telecom.TelecomManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;

import com.android.internal.telephony.ITelephony;
import com.dolawing.phonecallapp.blacknumber.db.BlackNumberDao;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 黑名单电话服务
 * @author liuyazhuang
 *
 */
public class BlackNumberService extends Service {

    private TelephonyManager tm;
    private MyPhoneStateListener listener;
    private BlackNumberDao blackNumberDao;
    private SharedPreferences sp;
    private NotificationManager nm;
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        sp = getSharedPreferences("config", Context.MODE_PRIVATE);
        listener = new MyPhoneStateListener();
        tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
        blackNumberDao = new BlackNumberDao(this);

        nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    }

    private final class MyPhoneStateListener extends PhoneStateListener{

        private long startTime = 0;
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            // TODO Auto-generated method stub
            super.onCallStateChanged(state, incomingNumber);
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:
                    //判断来电黑名单是否开启
                    boolean isblackstart = sp.getBoolean("isblacknumber", false);
                    if(isblackstart){
                        boolean isBlackNumber = blackNumberDao.isBlackNumber(incomingNumber);
                        if(isBlackNumber){
                            endCall2(incomingNumber);
                            return;
                        }
                    }

                    startTime = System.currentTimeMillis();

                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:

                    break;
                case TelephonyManager.CALL_STATE_IDLE:
                    long endTime = System.currentTimeMillis();
                    //来电一声响
                    if(endTime - startTime < 3000){
                        //发送通知
                        Notification notification = new Notification(android.R.drawable.stat_notify_missed_call, "拦截到来电一声响", System.currentTimeMillis());
                       // Intent intent = new Intent(getApplicationContext(),BlackNumberListActivity.class);
                      //  intent.putExtra("number", incomingNumber);
                       // PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 100, intent, 0);
                     //   notification.setLatestEventInfo(getApplicationContext(), "来电一声响", "拦截到来电一声响", contentIntent);
                        notification.flags = Notification.FLAG_AUTO_CANCEL;
                        nm.notify(100, notification);
                    }
                    break;

                default:
                    break;
            }
        }

    }
    //挂断电话
    private void endCall(String phone){
        boolean flag = false;//判断是否拦截成功
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            //1.得到电话管理者
            TelecomManager manager = (TelecomManager) getSystemService(Context.TELECOM_SERVICE);
            //2.得到电话号码
            String number = phone;
            if (manager != null) {
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ANSWER_PHONE_CALLS) != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(getApplicationContext(),"没有权限，拦截失败！",Toast.LENGTH_SHORT).show();
                }
                flag = manager.endCall();
            }
        }else{
            //1.得到电话管理者
            TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
            //2.得到电话号码
            String number = phone;
            Log.i("test","用户"+number+"来电了");
            //3.得到电话管理者类对象
            Class<TelephonyManager> clazz=TelephonyManager.class;
            try {
                //4.得到方法(的Method对象)
                Method method = clazz.getDeclaredMethod("getITelephony",null);
                //5.允许访问私有的方法
                method.setAccessible(true);
                //6.执行方法
                ITelephony iTelephony= (ITelephony) method.invoke(tm,null);
                //7.判断是不是这个号码是的话就挂断
                flag = iTelephony.endCall();//挂断电话
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
//        if(flag){
//            //删除通话记录 通话记录的保存是一个异步的操作，需要使用ContentObserver技术来实现
//            Uri uri = CallLog.Calls.CONTENT_URI;
//            getContentResolver().registerContentObserver(uri, true, new MyContentObserver(new Handler(),phone));
//            Toast.makeText(getApplicationContext(),"成功拦截",Toast.LENGTH_SHORT).show();
//        }
    }

//
//    //挂断电话
    private void endCall2(String phone) {
        boolean flag = false;//判断是否拦截成功
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            TelecomManager manager = (TelecomManager) getSystemService(Context.TELECOM_SERVICE);
            if (manager != null) {
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ANSWER_PHONE_CALLS) != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(getApplicationContext(),"没有权限，拦截失败！",Toast.LENGTH_SHORT).show();
                }
                flag = manager.endCall();
            }
        }else {
            //ITelephony.Stub.asInterface(ServiceManager.getService(Context.TELEPHONY_SERVICE));
            try {
                //获取类
                @SuppressLint("PrivateApi")
                Class<?> serviceManager = Class.forName("android.os.ServiceManager");
                //获取方法
                Method getService = serviceManager.getMethod("getService", String.class);
                //使用方法
                IBinder invoke = (IBinder) getService.invoke(null, Context.TELEPHONY_SERVICE);
                ITelephony iTelephony = ITelephony.Stub.asInterface(invoke);
                assert iTelephony != null;
                flag = iTelephony.endCall();
            } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException | RemoteException e) {
                e.printStackTrace();
            }
        }
        if(flag){
            //删除通话记录 通话记录的保存是一个异步的操作，需要使用ContentObserver技术来实现
            Uri uri = CallLog.Calls.CONTENT_URI;
            getContentResolver().registerContentObserver(uri, true, new MyContentObserver(new Handler(),phone));
            Toast.makeText(getApplicationContext(),"成功拦截",Toast.LENGTH_SHORT).show();
        }
    }


    private final class MyContentObserver extends ContentObserver {

        private String incomingNumber;
        public MyContentObserver(Handler handler, String incomingNumber) {
            super(handler);
            // TODO Auto-generated constructor stub
            this.incomingNumber = incomingNumber;
        }

        @Override
        public void onChange(boolean selfChange) {
            // TODO Auto-generated method stub
            super.onChange(selfChange);
            Uri uri = CallLog.Calls.CONTENT_URI;
            String where = CallLog.Calls.NUMBER + " = ?";
            String[] selectionArgs = new String[]{incomingNumber};
            getContentResolver().delete(uri, where, selectionArgs);

            //解除监听
            getContentResolver().unregisterContentObserver(this);
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }


    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        //取消状态监听
        tm.listen(listener, PhoneStateListener.LISTEN_NONE);
    }
}

